import React, { useState, useEffect, useCallback } from "react";
import {
  View,
  Text,
  ActivityIndicator,
  AsyncStorage,
  Image,
  StyleSheet
} from "react-native";
import { colors } from "../Style/Colors";
import { getPatientList, getIpdCount } from "../api/config";
import UserData from "../Data/UserData";
import Toast from "react-native-simple-toast";
import NetInfo from "@react-native-community/netinfo";

export const FetchData = props => {
  const [message, setMessage] = useState("");
  const [isConnected, setIsConnected] = useState(true);

  const handleConnectivityChange = isConnected => {
    setIsConnected(isConnected);
    if (isConnected) {
      getData();
    }
  };

  useEffect(() => {
    NetInfo.isConnected.addEventListener(
      "connectionChange",
      handleConnectivityChange
    );
    return () => {
      NetInfo.isConnected.removeEventListener(
        "connectionChange",
        this.handleConnectivityChange
      );
    };
  }, []);

  const getData = useCallback(() => {
    setMessage("Fetching user data");
    AsyncStorage.getItem("user-data")
      .then(d => {
        setMessage("Fetching OPD List");
        const data = JSON.parse(d);
        UserData.data = data;
        getPatientList("opd", data.Code || data.DrCode).then(v => {
          setMessage("Fetching IPD List");
          UserData.opdList = v;
          getPatientList("ipd", data.Code || data.DrCode).then(v1 => {
            setMessage("Fetching Discharge List");
            UserData.ipdList = v1;
            getPatientList("discharge", data.Code || data.DrCode).then(v2 => {
              setMessage("Getting IPD Count");
              UserData.dischargeList = v2;
              getIpdCount().then(v3 => {
                setMessage("All Data Fetched");
                UserData.ipdCount = v3;
                AsyncStorage.getItem("loggedin-user").then(val => {
                  if (val === "doctor") {
                    setMessage("Redirecting to the Doctor Dashboard");
                    props.navigation.navigate("App");
                  } else if (val === "houseman") {
                    setMessage("Redirecting to the Houseman Dashboard");
                    AsyncStorage.getItem("houseman-data").then(v4 => {
                      const data1 = JSON.parse(v4);
                      UserData.housemanData = data1;
                      props.navigation.navigate("Houseman");
                    });
                  }
                });
              });
            });
          });
        });
      })
      .catch(e => Toast.show(e.message));
  }, []);

  if (!isConnected) {
    return (
      <View style={styles.container}>
        <Image source={require("../assets/no_inter.png")} style={styles.img} />
        <View style={styles.textContainer}>
          <Text style={styles.title}>Oh No!</Text>
          <Text style={styles.subtitle}>
            No internet connection. Check your network and try again
          </Text>
        </View>
      </View>
    );
  }
  return (
    <View
      style={{
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: colors.whiteColor
      }}
    >
      <ActivityIndicator size="large" color={colors.primaryColor} />
      <Text style={styles.message}>{message}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: colors.whiteColor,
    padding: 20
  },
  img: {
    width: "100%",
    height: 300,
    resizeMode: "contain"
  },
  title: {
    fontWeight: "bold",
    fontSize: 28,
    color: colors.primaryColor
  },
  subtitle: {
    fontSize: 18,
    color: "#444",
    marginTop: 6,
    textAlign: "center"
  },
  textContainer: {
    justifyContent: "center",
    alignItems: "center"
  },
  message: {
    fontSize: 16,
    color: "#333",
    marginTop: 10
  }
});

export default FetchData;
